#!/bin/bash

r_host=$1
r_login=$2
#r_file=$3
local_folder=$3

path="/data/samba_share/imei/in/"
tmpfile="request_list"

print_usage()
{
   echo "Usage: $0 <remote host> <login> <remote file> <local folder>"
   echo "Download the given remote file of the given remote directory "
   echo "on the given remote host by using SSH protocol."
}

if [ "x$local_folder" == "x" ]; then
   echo "[ERROR] All arguments not available."
   print_usage
   exit 1
fi

C=`cat $tmpfile | wc -l`
if [ $C -eq 0 ]; then
    echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: No file found."
    exit
fi

for i in `cat $tmpfile`
  do
  file=`basename $i`
  #if [ -f $path$i -o $path"done/"$i -o $path"skipped/"$i -o $path"error"$i ]; then
  #echo "$path$file"
  #echo $path"done/"$file
  #if [ -f $path$file -o -f $path"done/"$file -o -f $path"error/"$file ]; then

  cat $path"../"log | grep $r_host | grep $file > /dev/null
  if [ $? -eq 0 ]; then
      echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: "$file" already retrieved! Skipping..." 
      continue
  fi
  
  echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: Retrieving file "$file"..." 
  scp $r_login@$r_host:"$i" $local_folder
  dos2unix $local_folder"/"$file > /dev/null 2>&1
  echo $r_host";"$file >> $path"../"log
done
